﻿CREATE PROCEDURE [branding].[ResolveText]
	@resourceId varchar(200),
	@tag varchar(50),
	@subTag varchar(50),
	@brand varchar(200)
AS
	declare @text table
	(
		TextId int,
		Brand varchar(200)
	)

	insert	@text (TextId, Brand)
	select	ID as TextId,
			Brand
	from	branding.[Text]
	where	ResourceId = @resourceId and
			(@tag is null or @tag = Tag) and
			(@subTag is null or @subTag = SubTag);

	select	top 1
			bt.ID,
			CAST('text' as varchar(10)) as ObjectType,
			bt.Tag,
			bt.SubTag,
			bt.ResourceId,
			bt.Brand,
			bt.ContentLength,
			bt.[Text]
	from	@text as t
	inner   join branding.[Text] as bt on bt.ID = t.TextId
	where   CHARINDEX(t.Brand, @brand) != 0
	order   by LEN(t.Brand) desc
RETURN 0